from mysql.connector import connect

class MySQLConnectionFactory:
    """MySQL连接工厂类"""
    
    def __init__(self):
        self.host = "localhost"
        self.user = "root"
        self.password = "123456"
        self.database = "elc_db"
        

    def get_connection(self):
        """获取数据库连接"""
        try:
            connection = connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database
            )
            return connection
        except Exception as e:
            raise Exception(f"数据库连接失败: {str(e)}")
            
    def execute_query(self, query: str, params: tuple = None) -> list[dict]:
        """执行查询并返回结果"""
        connection = self.get_connection()
        try:
            cursor = connection.cursor(dictionary=True)
            cursor.execute(query, params)
            results = cursor.fetchall()
            return results
        finally:
            if cursor:
                cursor.close()
            connection.close()
    
    def execute_update(self, query: str, params: tuple = None) -> int:
        """执行更新操作并返回受影响的行数"""
        connection = self.get_connection()
        try:
            cursor = connection.cursor()
            cursor.execute(query, params)
            connection.commit()
            return cursor.rowcount
        finally:
            if cursor:
                cursor.close()
            connection.close()
    def execute_insert(self, query: str, params: tuple = None) -> int:
        """执行插入操作并返回插入的ID"""
        connection = self.get_connection()
        try:
            cursor = connection.cursor()
            cursor.execute(query, params)
            connection.commit()
            return cursor.lastrowid
        finally:
            if cursor:
                cursor.close()
            connection.close()
    
    def execute_delete(self, query: str, params: tuple = None) -> int:
        """执行删除操作并返回受影响的行数"""
        connection = self.get_connection()
        try:
            cursor = connection.cursor()
            cursor.execute(query, params)   
            connection.commit()
            return cursor.rowcount
        finally:
            if cursor:
                cursor.close()
            connection.close()
    
